<!-- 求职者 -->
<template>
  <view class="container">
    <template v-if="showConversation">
      <!-- #ifdef MP-WEIXIN -->
      <!-- <tuicalling ref="TUICalling" id="TUICalling-component":config="config"></tuicalling> -->
      <!-- #endif -->
      <!-- <view class="headers"> -->
      <view class="tui-chatroom-navigatorbar">
        <!-- <image class="tui-chatroom-navigatorbar-back" src="/static/static/assets/ic_back_white.svg"  @tap="goBack"  />-->
        <u-icon
          name="arrow-left"
          color="#000000"
          class="tui-chatroom-navigatorbar-back"
          @tap="goBack"
        ></u-icon>
        <!-- 先查 remark；无 remark 查 (c2c)nick/(group)name；最后查 (c2c)userID/(group)groupID -->
        <view class="conversation-title">{{ conversationName }}</view>
      </view>
      <view v-if="hlistdata">
        <type-Jobhunting
          :hlistdata="hlistdata"
          @vupopupshow="jobvupopupshow"
        ></type-Jobhunting>
      </view>
      <!-- </view> -->
      <view class="group-profile">
        <TUI-group-profile
          v-if="isShow"
          id="groip-profile"
          :conversation="conversation"
        />
      </view>
      <!-- @tap="triggerClose" -->
      <view class="message-list" v-if="hlistdata">
        <TUI-message-list
          id="message-list"
          ref="messageList"
          :conversation="conversation"
          @youheadsculpture="youheadsculpture"
          @myheadsculpture="myheadsculpture"
          :hlistdata="hlistdata"
        />
      </view>
      <view v-if="videoPlay" class="container-box" @tap.stop="stopVideoHander">
        <video
          v-if="videoPlay"
          class="video-message"
          :src="videoMessage.payload.videoUrl"
          :poster="videoMessage.payload.thumbUrl"
          object-fit="cover"
          error="videoError"
          autoplay="true"
          direction="0"
        />
      </view>
      <view v-if="showChat" class="message-input">
        <TUI-message-input
          id="message-input"
          ref="messageInput"
          :conversation="conversation"
          @sendMessage="sendMessage"
        />
      </view>

      <!-- 自定义 -->
      <view v-if="upopupshow">
        <u-popup :show="upopupshow" mode="center" :round="10">
          <view class="upopupshownr">
            <view class="upopupshownrtop">
              <text>{{ upopupdata.text }}</text>
            </view>
            <view class="upopupshownrtext">
              <text>{{ upopupdata.textnr }}</text>
            </view>
            <view class="upopupshownrbut">
              <text class="upopupnrbut1" @click="upopupshow = false">取消</text>
              <text class="upopupnrbut2" @click="upopupclick">确定</text>
            </view>
          </view>
        </u-popup>
      </view>
      <view v-if="upoiashi">
        <Commonwords
          :upoiashi="upoiashi"
          @butfashofj="butfashofj"
        ></Commonwords>
      </view>
    </template>
  </view>
</template>

<script>
import logger from "@/utils/logger";
import TUIMessageList from "@/components/tui-chat/message-list/index";
import TUIMessageInput from "@/components/tui-chat/message-input/index";
import TUIGroupProfile from "@/components/tui-group/group-profile/index";

import Commonwords from "@/components/tui-chat/customchat/Commonwords";
import typeJobhunting from "@/components/tui-chat/customchat/typeJobhunting";

export default {
  components: {
    TUIMessageList,
    TUIMessageInput,
    TUIGroupProfile,
    typeJobhunting,
    Commonwords,
  },
  props: {},
  data() {
    return {
      conversationName: "",
      conversation: {},
      messageList: [],
      isShow: false,
      showChat: true,
      conversationID: "",
      videoPlay: false,
      videoMessage: {},
      config: {
        sdkAppID: "",
        userID: "",
        userSig: "",
        type: 1,
        tim: null,
      },
      hlistdata: {
        CorpName: "",
      },
      upoiashi: false,
      //附件消息
      dianjifujian: "",
      // //自定义
      upopupshow: false,
      upopupshowtext: [
        {
          id: "1",
          text: "提示",
          textnr: "确定发送手机号？",
        },
        {
          id: "2",
          text: "提示",
          textnr: "确定发送微信号？",
        },
      ],

      upopupdata: {
        id: "",
        text: "",
        textnr: "",
      },
    };
  },
  computed: {
    showConversation() {
      return !!this.conversation.conversationID;
    },
  },
  created() {
    uni.$on("videoPlayerHandler", (value) => {
      this.videoPlay = value.isPlay;
      this.videoMessage = value.message;
    });
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // conversationID: C2C、 GROUP
    logger.log(
      ` TUI-chat | onLoad | conversationID: ${options.conversationID}`
    );
    const { conversationID } = options;
    this.setData({
      conversationID,
    });
    // #ifdef MP-WEIXIN
    // this.config = {
    // 	sdkAppID: app.globalData.SDKAppID,
    // 	userID: app.globalData.userInfo.userID,
    // 	userSig: app.globalData.userInfo.userSig
    // }
    // logger.log(`TUI-chat | TUICalling-config  | config:${JSON.stringify(this.callingConfig)}`);
    // // 挂载在 uni 上
    // uni.$wxTUICalling = this.$refs.TUICalling;
    // 		this.$nextTick(() => {
    // 			uni.$wxTUICalling.init()
    // })
    // #endif

    //获取列表消息
    uni.$TUIKit.getConversationProfile(conversationID).then((res) => {
      const { conversation } = res.data;
      this.conversation = conversation;
      this.setData({
        conversationName: this.getConversationName(conversation),
        isShow: conversation.type === "GROUP",
      });
    });
  },
  mounted() {
    uni.$TUIKit
      .setMessageRead({
        conversationID: this.conversationID,
      })
      .then(() => {
        logger.log("TUI-chat | setMessageRead  | ok");
      });

    // 获取值
    this.getZhiwei(this.conversationID);
    this.$bus.$on("clickagree", this.clickagree);
    this.$bus.$on("clickrefuse", this.clickrefuse);
  },
  onUnload() {
    // #ifdef MP-WEIXIN
    //   this.$refs.TUICalling.destroyed();
    // // #endif
    this.$bus.$off("clickagree", this.clickagree);
    this.$bus.$off("clickrefuse", this.clickrefuse);
  },
  onShow() {
    this.upopupshow = false;
    this.upoiashi = false;
  },
  methods: {
    youheadsculpture() {
      uni.navigateTo({
        url: `/pages/views/packageA/type-jobhunting/search/JobDetails?id=${this.hlistdata.JobId}&showButton=false`,
      });
    },
    myheadsculpture() {
      uni.navigateTo({
        url: `/pages/views/packageB/type-jobhunting/resume/preview`,
      });
    },
    showjianlist() {
      this.upoiashi = true;
      this.dianjifujian = "";
    },
    jobvupopupshow(item) {
      if (item == 1) {
        this.upopupdata = this.upopupshowtext[0];
      } else if (item == 2) {
        this.upopupdata = this.upopupshowtext[1];
      }
      if (item == 3) {
        this.showjianlist();
      } else {
        this.upopupshow = true;
      }
    },
    close() {
      this.upoiashi = false;
    },
    // 发送附件 个人
    butfashofj(item) {
      this.upoiashi = false;
      if (item) {
        let e = this.dianjifujian;
        let objbut = {
          ExchangeResumeAttach: 1,
          ResumeAttachId: item.Id, //附件简历id 交换附件简历后
        };
        this.$http.huirc
          .jobUserRecordup({
            ...this.hlistdata,
            ...objbut,
          })
          .then((res) => {
            if (res.Success) {
              if (e) {
                const ext = JSON.parse(e.payload.extension);
                ext.ExchangeResumeAttach = objbut.ExchangeResumeAttach;
                ext.ExchangeResumetextname = item.Title;
                e.payload.extension = JSON.stringify(ext);
                uni.$TUIKit.modifyMessage(e);
                // 修改 当前状态
                this.systemtexttips("附件简历已发送");
              } else {
                let senderid = this.conversationID.split("_");
                this.systemtexttips("附件简历已发送");
              }
            }
          });
      }
    },
    qingk() {
      // 清空单聊的本地及云端的消息
      let promise = uni.$TUIKit.clearHistoryMessage(this.conversationID);
      promise
        .then(function (imResponse) {})
        .catch(function (imError) {
          // console.warn("clearHistoryMessage error:", imError); // 清空消息失败的相关信息
        });
    },
    //求职记录-单条查询
    getZhiwei(item) {
      let lisidst = item.split("_");
      const app = getApp();
      //CorpId 企业ID  JobUserId职位发布者ID
      this.$http.huirc
        .jobUserRecordget({
          userid: app.globalData.user.UserId, //用户ID
          jobuserid: lisidst[1], //职位创建者id
        })
        .then((res) => {
          if (res.Success) {
            this.hlistdata = res.Result;
            if (res.Result.HasChat === 0) {
              this.Senddefault();
            }
            //更新自定义会话数据
            const conversationID = item;
            const recordInfo = res.Result;
            uni.$TUIKit
              .setConversationCustomData({
                conversationIDList: [conversationID],
                customData: JSON.stringify({
                  CorpName: recordInfo.CorpName,
                }),
              })
              .then((res1) => {})
              .catch((imError) => {
                // console.warn("setConversationCustomData error:", imError);
              });
          }
        });
    },
    //发送 默认信息
    Senddefault() {
      let that = this;
      // 个人
      this.$http.core.phrasesdefault().then((res) => {
        if (res.Success) {
          if (res.Message) {
            that.textsendesage(res.Message);
          }
        }
      });
    },
    textsendesage(Content) {
      //个人给企业
      let that = this;
      if (this.showChat) {
        setTimeout(() => {
          that.$nextTick(() => {
            that.$refs.messageInput.sendTextMessage(Content, true);
          });
        }, 200);
      }
    },

    // 同意
    clickagree(e) {
      if (e.payload.data == "exchange-phone") {
        // 电话
        this.shenqingphont(e, {
          ExchangePhone: 1,
        });
      } else if (e.payload.data == "exchange-wechat") {
        // 微信
        this.shenqingexchangewechat(e, {
          ExchangeWechat: 1,
        });
      } else if (e.payload.data == "exchange-resume") {
        // 交换附件简历
        this.dianjifujian = e;
        this.upoiashi = true;
      } else if (e.payload.data == "job-interview") {
        this.miashiwechat(
          e,
          {
            InterviewState: 1,
          },
          true
        );
      } else if (e.payload.data == "job-employ") {
        this.employadd(e, {
          HasEmploy: 1,
        });
      }
    },
    // 拒绝
    clickrefuse(e) {
      if (e.payload.data == "job-interview") {
        let objbut = {
          InterviewState: 5,
        };
        this.miashiwechat(e, objbut, false);
      }
    },
    //申请手机号 个人确定
    shenqingphont(e, objbut) {
      this.$http.huirc
        .jobUserRecordup({
          ...this.hlistdata,
          ...objbut,
        })
        .then((res) => {
          if (res.Success) {
            const ext = JSON.parse(e.payload.extension);
            ext.ExchangePhone = objbut.ExchangePhone;
            e.payload.extension = JSON.stringify(ext);

            // 修改 当前状态
            uni.$TUIKit.modifyMessage(e);
            this.systemtexttips("手机号已发送");
          }
        });
    },

    //申请微信号 个人确定
    shenqingexchangewechat(e, objbut) {
      this.$http.huirc
        .jobUserRecordup({
          ...this.hlistdata,
          ...objbut,
        })
        .then((res) => {
          if (res.Success) {
            const ext = JSON.parse(e.payload.extension);
            ext.ExchangeWechat = objbut.ExchangeWechat;
            e.payload.extension = JSON.stringify(ext);
            // 修改 当前状态
            uni.$TUIKit.modifyMessage(e);
            this.systemtexttips("微信已发送");
          }
        });
    },
    // 已接受面试 已拒绝面试
    miashiwechat(e, objbut, type) {
      this.$http.huirc
        .jobUserRecordup({
          ...this.hlistdata,
          ...objbut,
        })
        .then((res) => {
          if (res.Success) {
            const ext = JSON.parse(e.payload.extension);
            ext.InterviewState = objbut.InterviewState;
            e.payload.extension = JSON.stringify(ext);
            // 修改 当前状态
            uni.$TUIKit.modifyMessage(e);
            if (type) {
              this.systemtexttips("已接受面试");
            } else {
              this.systemtexttips("已拒绝面试");
            }
          }
        });
    },

    // 添加录用 表
    employadd(e, objbut) {
      let obj = {
        UserId: this.hlistdata.UserId, //求职者用户ID
        JobId: this.hlistdata.JobId, //职位ID
      };
      const ext = JSON.parse(e.payload.extension);
      ext.HasEmploy = objbut.HasEmploy;
      e.payload.extension = JSON.stringify(ext);
      // 修改 当前状态
      uni.$TUIKit.modifyMessage(e);
      this.$http.huirc.employadd(obj).then((res) => {
        if (res.Success) {
          this.systemtexttips("已确定录用");
        }
      });
    },
    // 确定
    upopupclick() {
      this.upopupshow = false;
      let senderid = this.conversationID.split("_");
      if (this.upopupdata.id == 1) {
        this.$http.huirc
          .jobUserRecordup({
            ...this.hlistdata,
            ExchangePhone: 1,
          })
          .then((res) => {
            if (res.Success) {
              this.$refs.messageInput.$handleSendCustomMessage({
                detail: {
                  payload: {
                    data: "exchange-phone", //字段作为表示，可以自定义
                    description: "交换手机号",
                    extension: JSON.stringify({
                      JobId: this.hlistdata.JobId, //职位ID
                      JobName: this.hlistdata.JobName, //职位名称
                      UserId: this.hlistdata.UserId, //求职者ID
                      JobUserId: this.hlistdata.JobUserId, //职位发布者ID
                      UserName: this.hlistdata.UserName, //求职者名称
                      ExchangePhone: 1, //交换电话0 否 1是
                      UserPhoneNumber: this.hlistdata.UserPhoneNumber, //求职者电话
                      senderId: senderid[1], //对方聊天人id
                    }),
                  },
                },
              });
              this.systemtexttips("手机号已发送");
            }
          });
      } else if (this.upopupdata.id == 2) {
        this.$http.huirc
          .jobUserRecordup({
            ...this.hlistdata,
            ExchangeWechat: 1,
          })
          .then((res) => {
            if (res.Success) {
              this.$refs.messageInput.$handleSendCustomMessage({
                detail: {
                  payload: {
                    data: "exchange-wechat",
                    description: "交换微信",
                    extension: JSON.stringify({
                      JobId: this.hlistdata.JobId, //职位ID
                      JobName: this.hlistdata.JobName, //职位名称
                      UserId: this.hlistdata.UserId, //求职者ID
                      JobUserId: this.hlistdata.JobUserId, //职位发布者ID
                      UserName: this.hlistdata.UserName, //求职者名称
                      ExchangeWechat: 1, //交换微信0 否 1是
                      UserWechat: this.hlistdata.ResumeInfo.WeixinNo, //求职者微信
                      senderId: senderid[1], //对方聊天人id
                    }),
                  },
                },
              });
              this.systemtexttips("微信已发送");
            }
          });
      }
    },

    // 消息描述
    systemtexttips(item) {
      this.$refs.messageInput.$handleSendCustomMessage({
        detail: {
          payload: {
            data: "system-text-tips",
            description: item,
          },
        },
      });
    },
    stopVideoHander() {
      this.videoPlay = false;
    },
    getConversationName(conversation) {
      if (conversation.type === "@TIM#SYSTEM") {
        this.setData({
          showChat: false,
        });
        return "系统通知";
      }
      if (conversation.type === "C2C") {
        return (
          conversation.remark ||
          conversation.userProfile.nick ||
          conversation.userProfile.userID
        );
      }
      if (conversation.type === "GROUP") {
        return (
          conversation.groupProfile.name || conversation.groupProfile.groupID
        );
      }
    },
    sendMessage(event) {
      // 将自己发送的消息写进消息列表里面
      this.$refs.messageList.updateMessageList(event.detail.message);
    },
    // triggerClose() {
    //   if (this.showChat) {
    //     this.$refs.messageInput.handleClose();
    //   }
    // },
    goBack() {
      const pages = getCurrentPages(); // 当前页面栈
      if (
        pages[pages.length - 2].route ===
          "pages/TUI-Conversation/create-conversation/create" ||
        pages[pages.length - 2].route ===
          "pages/TUI-Group/create-group/create" ||
        pages[pages.length - 2].route === "pages/TUI-Group/join-group/join"
      ) {
        uni.navigateBack({
          delta: 2,
        });
      } else {
        uni.navigateBack({
          delta: 1,
        });
      }
      uni.$TUIKit
        .setMessageRead({
          conversationID: this.conversationID,
        })
        .then(() => {});
    },
  },
};
</script>


<style>
@import "./chat.css";
</style>

<style lang="scss" scoped>
.headers {
  position: fixed;
  z-index: 999;
}

.upopupshownr {
  padding: 40rpx 60rpx;
  text-align: center;
  width: 550rpx;

  .upopupshownrtop {
    font-weight: bold;
    font-size: 32rpx;
  }

  .upopupshownrtext {
    padding: 60rpx 0rpx;
    font-size: 30rpx;
    font-weight: bold;
  }

  .upopupshownrbut {
    padding-top: 40rpx;
    display: flex;
    justify-content: space-around;

    .upopupnrbut1 {
      border: 1px solid #a0a0a0;
      display: inline-block;
      padding: 20rpx 60rpx;
      border-radius: 10rpx;
      font-size: 26rpx;
      color: #999999;
    }

    .upopupnrbut2 {
      display: inline-block;
      padding: 20rpx 60rpx;
      border-radius: 10rpx;
      font-size: 26rpx;
      background-color: #1684fc;
      color: #ffffff;
    }
  }
}
</style>